package com.boarsoft.message.sofamq;

import java.io.Closeable;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.openmessaging.api.Message;

public class SofaMQClient implements Closeable {
	private static final Logger log = LoggerFactory.getLogger(SofaMQClient.class);

	/** 队列列表 */
	protected Map<String, SofaMQDestination> destMap;

	@PostConstruct
	public void init() {
		for (Entry<String, SofaMQDestination> en : destMap.entrySet()) {
			String key = en.getKey();
			SofaMQDestination dest = en.getValue();
			dest.setCode(key);
			// 初始化此队列的消费者
			SofaMQConsumer consumer = dest.getConsumer();
			if (consumer != null) {
				consumer.init(dest.getCode());
			}
			// 初始化此队列的生产者
			SofaMQProducer producer = dest.getProducer();
			if (producer != null) {
				producer.init();
			}
		}
	}

	/**
	 * 外发消息
	 *
	 * @param msg
	 * @param target
	 * @throws Exception
	 */
	public void put(Message m, String target) throws Exception {
		SofaMQDestination dest = destMap.get(target);
		SofaMQProducer producer = dest.getProducer();
		try {
			producer.sendMessage(m);
		} catch (Throwable e) {
			throw e;
		}
	}

	@Override
	public void close() {
		for (SofaMQDestination dest : destMap.values()) {
			try {
				dest.close();
			} catch (Exception e) {
				log.error("Error on close SofaMQ destination {}", dest, e);
			}
		}
	}

	public void setDestMap(Map<String, SofaMQDestination> destMap) {
		this.destMap = destMap;
	}
}
